import React, {
  useState,
  useCallback,
  useLayoutEffect,
  memo,
  useEffect,
} from 'react';
import { Button, Alert, List } from 'antd';

// const set = new Set();
/**
 * 应用场景：考虑到性能优化，在更新苹果count状态值时，不渲染子页面呢？
 * 解决方案：使用useCallback和memo
 */
export default () => {
  const [miCount, setMiCount] = useState(0);
  const [appleCount, setAppleCount] = useState(0);

  /**
   * @description 计算小米手机当前销售额
   * 这里用useCallback包裹要处理的函数，用法和useEffect类似，但是不会主动执行，只有被调用的时候才执行
   * useCallback的返回是缓存的函数，即handleCalc仍然是函数
   */
  const handleCalc = useCallback(() => {
    console.log('----进入复杂逻辑----');
    // 真实案例中，会有复杂的计算逻辑，会特别消耗性能
    return miCount * 3980;
  }, [miCount]);

  // set.add(handleCalc);

  const renderMessage = () => {
    return <div>222</div>;
  };

  return (
    <>
      {console.log('----父组件页面渲染----')}
      <div>
        <Alert message={renderMessage()} />
        {/* {set.size} */}
        <Child callback={handleCalc} />
      </div>
      <div>
        <span style={{ marginRight: 6 }}>
          {`小米手机当前售出：${miCount} 台`}
        </span>
        <span>
          <Button onClick={() => setMiCount(miCount + 1)}>+1</Button>
        </span>
      </div>
      <div>
        <span style={{ marginRight: 6 }}>
          {`苹果手机当前售出：${appleCount} 台`}
        </span>
        <span>
          <Button onClick={() => setAppleCount(appleCount + 1)}>+1</Button>
        </span>
      </div>
    </>
  );
};

const Child = memo((props: any) => {
  const { callback } = props;
  const [applePrice, setApplePrice] = useState(() => callback());
  useLayoutEffect(() => {
    setApplePrice(callback());
  }, [callback]);

  return (
    <div>
      {console.log('----子组件渲染----')}
      {`小米手机当前销售额：${applePrice} 元`}
    </div>
  );
});
